{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e9623f14-d764-4cf8-982c-89bb29ad79bd",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'KNeighborsRegressor' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[7], line 11\u001b[0m\n\u001b[0;32m      9\u001b[0m k_error\u001b[38;5;241m=\u001b[39m[]\n\u001b[0;32m     10\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m k \u001b[38;5;129;01min\u001b[39;00m k_range:\n\u001b[1;32m---> 11\u001b[0m     model\u001b[38;5;241m=\u001b[39mKNeighborsRegressor(n_neighbors\u001b[38;5;241m=\u001b[39mk)\n\u001b[0;32m     12\u001b[0m     model\u001b[38;5;241m.\u001b[39mfit(x_train,y_train)\n\u001b[0;32m     13\u001b[0m     scores\u001b[38;5;241m=\u001b[39mmodel\u001b[38;5;241m.\u001b[39mscore(x_test,y_test)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'KNeighborsRegressor' is not defined"
     ]
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "x=np.array([[182],[178],[170],[168],[165],[162],[158],[154],[149],[144]])\n",
    "y=np.array([[113],[105],[86 ],[83],[86],[74],[72],[45],[49],[43]])\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)\n",
    "k_range=range(2,8)\n",
    "k_error=[]\n",
    "for k in k_range:\n",
    "    model=KNeighborsRegressor(n_neighbors=k)\n",
    "    model.fit(x_train,y_train)\n",
    "    scores=model.score(x_test,y_test)\n",
    "    k_error.append(1-scores)\n",
    "plt.rcParams['font.sans-serif']='Simhei'\n",
    "plt.plot(k_range,k_error,'r-')\n",
    "plt.xlabel('k的取值')\n",
    "plt.ylabel('预测误差率')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c80f1b68-f5ef-432e-b363-86b3f20a9c70",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
